package controller.addtextServlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import bean.Filesf;
import dao.util.FilesCreate;
import bean.User;

import java.io.IOException;
import java.io.InputStream;

@WebServlet("/mynote/Upload")
@MultipartConfig(
        maxFileSize = 1024*1024*10,
        maxRequestSize = 1024*1024*100
)
public class Upload extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        // 优先从 session 获取当前登录用户
        User currentUser = null;
        if (req.getSession(false) != null) {
            currentUser = (User) req.getSession(false).getAttribute("user");
        }
        String username = currentUser != null ? currentUser.getUsername() : req.getParameter("username");
        Part filePart = req.getPart("file");
        String filename = filePart.getSubmittedFileName();
        // 把文件内容读到 byte[]
        byte[] fileBytes;
        try (InputStream inputStream = filePart.getInputStream()) {
            fileBytes = inputStream.readAllBytes();
        }

        Filesf fileEntity = new  Filesf();
        fileEntity.setUsername(username);
        if (currentUser != null) {
            fileEntity.setUserId(currentUser.getId());
        }
        fileEntity.setFilename(filename);
        fileEntity.setFiledata(fileBytes);
        fileEntity.setFiletype(filePart.getContentType());  // 文件类型（如 image/png, application/pdf）
        fileEntity.setFilesize(filePart.getSize());         // 文件大小（字节数）
        fileEntity.setUploadTime(new java.util.Date());     // 上传时间（当前时间）

        FilesCreate filesCreate = new FilesCreate();
        filesCreate.getMapperClass().insertFile(fileEntity);
        filesCreate.commitsession();
        filesCreate.closesession();
        // 上传成功提示 + 跳转回 post.html
        resp.getWriter().write("上传成功，即将返回提交界面...");

// 3秒后自动跳转
        resp.setHeader("refresh", "3;url=" + req.getContextPath() + "/post.html");

    }
}
